<?php
// 初始化设置
header('Content-Type: application/json');
$uploadDir = __DIR__ . '/uploads/';
if (!is_dir($uploadDir)) mkdir($uploadDir, 0755);

// 生成6位取件码
function generateCode() {
    $chars = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789'; // 排除易混淆字符
    $code = '';
    for ($i=0; $i<6; $i++) {
        $code .= $chars[random_int(0, strlen($chars)-1)];
    }
    return $code;
}

try {
    // 接收数据
    $expireHours = $_POST['expire'] ?? 24;
    $expireTime = date('Y-m-d H:i:s', time() + $expireHours * 3600);
    $code = generateCode();

    // 处理文件上传
    if (!empty($_FILES['file']['name'])) {
        $file = $_FILES['file'];
        $maxSize = 5 * 1024 * 1024; // 5MB限制
        
        if ($file['size'] > $maxSize) {
            throw new Exception("文件大小超过5MB限制");
        }

        $allowedTypes = ['pdf', 'docx', 'jpg', 'png'];
        $fileExt = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
        if (!in_array($fileExt, $allowedTypes)) {
            throw new Exception("不支持的文件类型");
        }

        $filename = $code . '_' . basename($file['name']);
        move_uploaded_file($file['tmp_name'], $uploadDir . $filename);
    } 
    // 处理文本内容
    elseif (!empty($_POST['text'])) {
        $filename = $code . '_text.txt';
        file_put_contents($uploadDir . $filename, $_POST['text']);
    } else {
        throw new Exception("请选择文件或输入文本内容");
    }

    // 数据库记录
    $db = new SQLite3('database.db');
    $stmt = $db->prepare('
        INSERT INTO files (code, filename, original_name, expire_time) 
        VALUES (:code, :fn, :org, :exp)
    ');
    $stmt->bindValue(':code', $code);
    $stmt->bindValue(':fn', $filename);
    $stmt->bindValue(':org', $_FILES['file']['name'] ?? '文本内容.txt');
    $stmt->bindValue(':exp', $expireTime);
    $stmt->execute();

    echo json_encode([
        'status' => 'success',
        'code' => $code,
        'expire' => $expireTime,
        'qr_url' => "https://api.qrserver.com/v1/create-qr-code/?size=150x150&data={$code}"
    ]);

} catch (Exception $e) {
    http_response_code(400);
    echo json_encode([
        'status' => 'error',
        'message' => $e->getMessage()
    ]);
}
